package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")

public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       /* HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String path = request.getServletPath();
        //判断是否为登录请求，如果是登录请求，则放行
        if (path.contains("/login")){
            log.info("登录请求:{},放行...", path);
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头 token
        String token = request.getHeader("token");
        //判断token是否存在，如果不存在，则返回401错误
        if (token == null ||token.isEmpty()){
            log.info("token不存在，返回401错误...");
            response.setStatus(401);
            return;
        }
        //校验token
        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            log.info("token验证失败，返回401错误...");
            response.setStatus(401);
            return;
        }
        //放行
        filterChain.doFilter(request,response);*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        //判断是否是登录请求，如果是，则放行
        if (path.contains("/login")){
            log.info("登录请求:{},放行...", path);
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头 token
        String token = request.getHeader("token");
        //判断token是否存在，如果不存在，则返回401错误
        if (token ==null || token.isEmpty()){
            log.info("token不存在，返回401错误...");
            response.setStatus(401);
            return;
        }
        //校验token
        try {
            Claims claims =JwtUtils.parseToken(token);
            //获取用户id
            Integer userId = claims.get("id",Integer.class);
            CurrentUserHoler.setCurrentUser(userId);
        }catch (Exception e){
            log.info("token验证失败，返回401错误...");
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(request,response);
        //删除当前用户
        CurrentUserHoler.removeCurrentUser();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
